package com.example.user_manage.Component;

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class ApplicationShutdownListener implements ApplicationListener<ContextClosedEvent> {

    /**
     * redis数据库操作对象
     */
    private final RedisTemplate<String,Object> redisTemplate;

    /**
     * 主程序关闭时调用
     * @param event 事件
     */
    @Override
    public void onApplicationEvent(@NonNull ContextClosedEvent event) {
        System.out.println("服务器关闭中...");

        if(redisTemplate.getConnectionFactory() != null){
            try (RedisConnection connection = redisTemplate.getConnectionFactory().getConnection()) {
                //清理数据库缓存
                connection.serverCommands().flushDb();
            }
            //关闭连接
        }

        System.out.println("服务器关闭");

    }
}
